"use client";
import { useSetCookie, useGetCookie } from "cookies-next/client";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { useEffect, useState } from "react";
import { defaultLocale, getLanguage, languages, Locale } from "@/i18n/config";
import { useRouter } from "next/navigation";
import { LanguagesIcon } from "lucide-react";

export default function LanguageSwitcher() {
  const setCookie = useSetCookie();
  const getCookie = useGetCookie();
  const [curLang, setCurLang] = useState<Locale>(defaultLocale);
  useEffect(() => {
    setCurLang(getCookie("locale") as Locale);
  }, [getCookie]);
  const router = useRouter();
  const handle = (locale: string) => {
    setCookie("locale", locale, {
      expires: new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000),
    }); // 365d
    setCurLang(locale as Locale);
    router.refresh();
  };

  return (
    <Popover>
      <PopoverTrigger asChild>
        <div className="w-20 flex items-center text-sm gap-2 cursor-pointer group">
          <LanguagesIcon size={14} className="text-muted-foreground group-hover:text-primary" />
          <div className="text-muted-foreground group-hover:text-primary">
            {getLanguage(curLang)?.label ?? getLanguage(defaultLocale)?.label}
          </div>
        </div>
      </PopoverTrigger>
      <PopoverContent className="w-auto flex flex-col gap-2">
        {languages.map((lang) => (
          <div
            key={lang.value}
            onClick={() => handle(lang.value)}
            className={cn("cursor-pointer text-sm text-muted-foreground", {
              "text-primary font-bold": lang.value === curLang,
            })}
          >
            {lang.label}
          </div>
        ))}
      </PopoverContent>
    </Popover>
  );
}
